import React, { PureComponent, Fragment ,Component} from 'react';
import { connect } from 'dva';
import { routerRedux } from 'dva/router';
import {
  Row, Col, Card, Form, Input, Select, Icon, Button, Modal, message, Badge, Divider, Tag, Popconfirm,
} from 'antd';
import StandardTable from 'components/StandardTable';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import { Map } from 'react-amap';
import styles from './Store.less';
import { imgPrex } from '../../utils/constData';
const QRCode = require('qrcode.react');
const FormItem = Form.Item;
const { Option } = Select;
let qrCode={}
const CreateForm = Form.create()(props => {
  const { modalVisible, form, handleOk, handleCancel, loading } = props;
  const okHandle = () => {
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      handleOk(fieldsValue);
    });
  };
  return (
    <Modal
      title= ""
      visible={modalVisible}
      onOk={okHandle}
      onCancel={() => handleCancel(false)}
      width="250px"
      closable={false}
      footer={null}
      centered={true}
    >
      <div>
       <QRCode size={190} value={qrCode.url}/>
      </div>
    </Modal>
  );
});


@connect(({ store, loading }) => ({
  store,
  pagination: store.pagination,
  loading: loading.models.store,
}))
@Form.create()
export default class Store extends PureComponent {
  state = {
    selectedRows: [],
    zhuangtai:1,
    qrCode:{},
  };

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'store/fetchStoreList',
      payload: { 'pageNum': '0', 'pageSize': '0' }
    });
  }


_setModalVisible(flag) {
    if (!flag) {
      this.setState({
        modalVisible: flag,
      })
    } else {
      this.setState({
        modalVisible: flag,
      })
    }
  }
  handleFormReset = () => {
    const { form, dispatch } = this.props;
    form.resetFields();
    const params = {
      pageNum: 1,
      pageSize: 20,
    };
    dispatch({
      type: 'store/fetchStoreList',
      payload: params,
    });
  };


  handleSearch() {
    const { dispatch, form } = this.props;
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      const values = {
        ...fieldsValue,
        pageNum: 1,
        pageSize:  20,
      };

      dispatch({
        type: 'store/fetchStoreList',
        payload: values,
      });
    });
  };

deleteStore(storeid,e){
  const params={
    storeId:storeid
  }
  this.props.dispatch({
    type: 'store/delStore',
    payload: params,
    callback: () => this.callback()
  });
}

showQRcode(storeid,franid,e){
  console.log(storeid+'-----'+franid)
  const params={
    franStoreId:storeid,
    franId:franid,
    ticketType:1
  }
  this.props.dispatch({
    type: 'store/getFranchiserQRCode',
    payload: params,
  }).then(()=>{
    const {store} = this.props
    qrCode =store.qrCode
    console.log(qrCode)
    this._setModalVisible(true)
  })
  
}

  _changeStoreStatus(storeid,storests,e) {
    let itemid= storeid
    let itemsta= storests
    let recordList = {}
    //recordList.push({ storeId: itemid })
    if(itemsta == 1){
      let changedsts = 2
      const params = {
        storeId: itemid,
        storeSts: changedsts,
      };
      this.props.dispatch({
          type: 'store/updateStoreSts',
          payload: params,
          callback: () =>{
            this.props.dispatch({
            type: 'store/fetchStoreList',
            payload: { pageNum: 1,pageSize:  20,},
            callback: () => this.callback()
          });
          }
        });    
    }else if(itemsta == 2) {
        let changedsts = 1
        const params = {
        storeId: itemid,
        storeSts: changedsts,
      };
      this.props.dispatch({
            type: 'store/updateStoreSts',
            payload: params,
            callback: () =>{
              this.props.dispatch({
              type: 'store/fetchStoreList',
              payload: { pageNum: 1,pageSize:  20,},
              callback: () => this.callback()
            });
          }
          });
      }   
  }

  callback() {
    this.handleSearch()
  }

_handleCancel(flag, form) {
    this._setModalVisible(flag);
  }


  renderAdvancedForm() {
    const { form } = this.props;
    const { getFieldDecorator } = form;
    return (
      <Form layout="inline">
      <div style={{ overflow: 'hidden' }}>
          <div className={styles.mendTitle}>门店管理-门店维护</div>
          <span style={{ float: 'right', marginBottom: 24 }}>
            <Button onClick={this.handleFormReset} style={{ border:'none' ,color:'#80829e'}}>
              重置
            </Button>
            <Button style={{ marginLeft: 12 }} className={styles.serachButton} type="primary" htmlType="submit" onClick={() => this.handleSearch()}>
              查询
            </Button>
          </span>
        </div>
        <Row style={{border:'1px dashed #ccc',padding:'30px 10px 0',marginBottom:20,position:'relative'}} gutter={{ md: 8, lg: 24, xl: 48 }}>
          <div className={styles.absoluteposition}>门店信息</div>
          <Col md={8} sm={24}>
            <FormItem label="门店名称">
              {getFieldDecorator('storeName')(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="门店状态">
              {getFieldDecorator('storeSts', { initialValue: 'undefined' })(
                <Select style={{ width: '100%' }}>
                  <Option value="undefined">全部</Option>
                  <Option value="1">营业中</Option>
                  <Option value="2">歇业中</Option>
                </Select>
              )}
            </FormItem>
          </Col>
        </Row>

        
      </Form>
    );
  }


  render() {
    const { store, loading, storeList} = this.props;
    const {modalVisible}=this.state
    const storelist = store.storeList
    console.log(store)
    const storeInfo = storelist.list && storelist.list.map(item =>{
      return (<Col span={6} style={{marginBottom:30}}>
              <div className={styles.mendiandiv}>
                <div className={styles.mendianName}>
                  <div>{item.storeName}</div>
                  <div>
                  <Icon className={styles.cusor} type="form" theme="outlined" onClick={() => this.props.dispatch(routerRedux.push({ pathname: '/store/editstore/'+item.storeId }))} title='编辑门店' />
                  <Icon className={styles.cusor} type="qrcode" theme="outlined" onClick={(e) => this.showQRcode(item.storeId,item.franId,e)} title='显示二维码'/>
                  <Icon className={styles.cusor} type="lock" theme="outlined" onClick={(e) =>this._changeStoreStatus(item.storeId,item.storeSts,e)} title='切换状态'/>
                  <Icon className={styles.cusor} type="delete" theme="outlined" onClick={(e) =>this.deleteStore(item.storeId,e)} title='删除门店'/>
                  </div>
                </div>
                { item.storeSts ==1 ?(<div className={styles.mendzhuangtOne}>营业中</div>):(<div className={styles.mendzhuangtTwo}>歇业中</div>)}
                <div className={styles.mendjiams}>{item.franName}</div>
                <div className={styles.mendshijian}>营业时间：{item.startSts == 0 ? (<span>全天</span>):(<span>{item.startTime}-{item.endTime}</span>)}</div>
                <div className={styles.mendshijian}>创建时间：{item.createTime}</div>
                <div className={styles.mendshijian}>门店编号：{item.storeId}</div>
              </div>
            </Col>)
    })


    return (
      <PageHeaderLayout title="" className={styles.storeStyle}>
        <Card bordered={false}>
          <div className={styles.tableList}>
            <div className={styles.tableListForm}>{this.renderAdvancedForm()}</div>
            <div className={styles.tableListOperator}>
              <Button className={styles.addStoreButton} type="primary" onClick={() => this.props.dispatch(routerRedux.push({ pathname: '/store/editstore/new' }))}>
                新增门店
              </Button>
            </div>

          </div>
        </Card>
        <div className={styles.mendianNUm}>门店数量：{storelist.total}</div>
        <Row gutter={16} style={{marginBottom:30}}>
          {storeInfo}
        </Row>
        <CreateForm handleOk={(fieldsValue) => this._handleOk(fieldsValue)} modalVisible={modalVisible}
          handleCancel={(flag) => this._handleCancel(flag)} 
        />
      </PageHeaderLayout>
    );
  }
}
